<template>
  <div class="app-container">
    <div class="card-box">
      <el-table :data="taskStore.list" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="任务名称" />
        <el-table-column prop="target_url" label="目标URL" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="statusTagType(row.status)">
              {{ statusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="curr_execute_count" label="执行次数" />
        <el-table-column prop="created_at" label="创建时间" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button link @click="handleDetail(row.id)">详情</el-button>
            <el-popconfirm
              title="是否确认删除？"
              confirm-button-text="确定"
              cancel-button-text="取消"
              type="danger"
              @confirm="handleDelete(row.id)"
            >
              <template #reference>
                <el-button link type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-model:page="listQuery.page"
        v-model:limit="listQuery.size"
        :total="taskStore.totalCount"
        @pagination="fetchData"
      />
    </div>
    <Detail v-if="currentDetail" v-model="detailVisible" :detail="currentDetail" />
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted } from "vue";
import { useTaskStoreHook } from "@/store/modules/task/task";
import Pagination from "@/components/Pagination/index.vue";
import Detail from "./components/Detail.vue";
import { TaskType } from "@/api/task/task";

const taskStore = useTaskStoreHook();

const listQuery = reactive({
  page: 1,
  size: 20,
});

function statusText(status: string) {
  const map: Record<string, string> = {
    pending: "待处理",
    processing: "执行中",
    success: "成功",
    failed: "失败",
  };
  return map[status] || status;
}

function statusTagType(status: string): any {
  const map: Record<string, string> = {
    pending: "info",
    processing: "warning",
    success: "success",
    failed: "danger",
  };
  return map[status] || "";
}

async function fetchData() {
  await taskStore.fetchList(listQuery);
}

const detailVisible = ref(false);
const currentDetail = ref<TaskType | null>(null);

async function handleDetail(id: number) {
  currentDetail.value = await taskStore.fetchDetail(id);
  detailVisible.value = true;
}

async function handleDelete(id: number) {
  await taskStore.fetchDelete(id);
  fetchData();
}

onMounted(() => {
  fetchData();
});
</script>

// 在模板末尾添加Detail组件
<Detail v-model="detailVisible" :detail="currentDetail" v-if="currentDetail" />
